package com.example.auth.utils;

import com.example.auth.constants.CommonConstants;
import com.example.auth.model.SysClient;
import com.example.auth.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.security.PublicKey;

/**
 * Created by wangtao on 2018/3/2.
 */
public class JwtHelper {
    private Logger logger = LoggerFactory.getLogger(JwtHelper.class);
    @Value("${jwt.user.pubKey.path}")
    private String userPubKeyPath;
    @Value("${jwt.client.pubKey.path}")
    private String clientPubKeyPath;

    /**
     * 解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
        PublicKey publicKey = KeyHelper.getPublicKey(pubKeyPath);
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
        return claimsJws;
    }

    /**
     * 从token中解析用户信息
     *
     * @param token
     * @return
     */
    public User getUserByToken(String token) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, userPubKeyPath);
        Claims body = claimsJws.getBody();
        User user = new User(body.get(CommonConstants.JWT_KEY_USER_ID, Long.class), body.get(CommonConstants.JWT_KEY_USER_NAME, String.class), body.getSubject(),null,null,null,null,null,null,null,null,null,null,null,null,null);
        return user;
    }

    /**
     * 从token中解析用户信息
     *
     * @param token
     * @return
     */
    public SysClient getClientByToken(String token) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, clientPubKeyPath);
        Claims body = claimsJws.getBody();
        SysClient client = new SysClient(body.get(CommonConstants.JWT_KEY_CLIENT_ID, Long.class), body.getSubject(), body.getSubject(), body.get(CommonConstants.JWT_KEY_CLIENT_SECRET, String.class));
        return client;
    }
}
